package com.ruoyi.pingjiao.service.impl;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.pingjiao.domain.*;
import com.ruoyi.pingjiao.domain.query.CoureassessQueryParam;
import com.ruoyi.pingjiao.domain.vo.*;
import com.ruoyi.pingjiao.mapper.*;
import com.ruoyi.pingjiao.service.*;
import com.ruoyi.pingjiao.utils.CourseassessTree;
import com.ruoyi.pingjiao.utils.WordUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
public class CourseAssessNameServiceImpl implements CourseAssessNameService {
    @Autowired
    private CourseAssessNameMapper courseAssessNameMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private ScoreService scoreService;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private  CourseAssessService courseAssessService;
    @Autowired
    private ICourseService courseService;
    @Autowired
    private AchievementDistributionMapper achievementDistributionMapper;
    @Autowired
    private CoureassessAverageMapper coureassessAverageMapper;
    @Override
    public CourseassessName selectByCourseAssessId(Long id) {
        return courseAssessNameMapper.selectByCourseAssessId(id);
    }

    @Override
    public List<CourseassessName> selectByCourseAssessIdAndParentId(Long id) {
        return courseAssessNameMapper.selectByCourseAssessIdAndParentId(id);
    }

    @Override
    public int count() {
        return courseAssessNameMapper.count();
    }

    @Override
    public List<CourseassessName> selectName(Long teacherId,Long courseassessId) {
        Map<String,Object>map=new HashMap<>();
        map.put("teacherId",teacherId);
        map.put("coureassessId",courseassessId);
        return courseAssessNameMapper.selectName(map);
    }

    @Override
    @Transactional
    public List<CourseassessName> list(CoureassessQueryParam coureassessQueryParam) {
        System.out.println(coureassessQueryParam);
        ArrayList<Coureassess> coureassessList = courseAssessService.list((Integer) coureassessQueryParam.getCourseId().intValue());
        List<CourseassessName> list = new ArrayList<>();
        Long id = 1000L;
        for (Coureassess coureassess : coureassessList) {
            CourseassessName courseassessName = new CourseassessName();
            courseassessName.setName(coureassess.getCourseassess());
            courseassessName.setCoureassessId(coureassess.getId());
            courseassessName.setId(id);
            id ++;
            list.add(courseassessName);
        }

        for (CourseassessName courseassessName : list) {
            List<CourseassessName> list1 = courseAssessNameMapper.selectByCourseAssessIdList(courseassessName.getCoureassessId());
            courseassessName.setChildren(list1);
        }
//        for (Coureassess coureassess : coureassessList) {
//            List<CourseassessName> courseassessNames = courseAssessNameMapper.selectByCourseAssessIdList(coureassess.getId());
//            coureassess.setCourseassessNameList(courseassessNames);
//        }

//        List<CourseassessName> list = courseAssessNameMapper.list(courseassessName);
//        System.out.println(list);
//        List<CourseassessName> courseassessNameList = CourseassessTree.makeTree(list, 0L);
        Long userId = SecurityUtils.getUserId();
        Teacher teacher = teacherMapper.selectTeacherByUserId(userId);
//        for (CourseassessName c:list
//             ) {
////            Teacher teacher = teacherMapper.selectTeacherByTeacherId(c.getTeacherId());
//            c.setTeacherName(teacher.getRealName());
//        }

//        for (Coureassess coureassess : coureassessList) {
//            for (CourseassessName courseassessName : coureassess.getCourseassessNameList()) {
//                courseassessName.setTeacherName(teacher.getRealName());
//            }
//        }
        for (CourseassessName courseassessName : list) {
            courseassessName.setTeacherName(teacher.getRealName());
        }
        return list;
    }

    @Override
    public List<CourseassessName> listAll(CourseassessName courseassessName) {
        List<CourseassessName> list = courseAssessNameMapper.list(courseassessName);
//        List<CourseassessName> courseassessNameList = CourseassessTree.makeTree(list, 0L);
        Long userId = SecurityUtils.getUserId();
        Teacher teacher = teacherMapper.selectTeacherByUserId(userId);
        for (CourseassessName c:list
        ) {
//            Teacher teacher = teacherMapper.selectTeacherByTeacherId(c.getTeacherId());
            c.setTeacherName(teacher.getRealName());
        }
        return list;
    }

    @Override
    public int add(CourseassessName courseassessName) {
//        Long userId = SecurityUtils.getUserId();
//        Teacher teacher = teacherMapper.selectTeacherByUserId(userId);
//        courseassessName.setTeacherId(teacher.getTeacherId());
        courseassessName.setCreateTime(new Date());
        return courseAssessNameMapper.add(courseassessName);
    }

    @Override
    public int updateInfo(CourseassessName courseassessName) {
//        Score score=new Score();
//        score.setWokeName(courseassessName.getName());
//        score.setPercents(Double.valueOf(courseassessName.getPercent()));
//        scoreService.updateInfo(score);
        courseassessName.setUpdateTime(new Date());
        return courseAssessNameMapper.update(courseassessName);
    }

    @Override
    public int delete(Long[] id) {
        return courseAssessNameMapper.delete(id);
    }

    @Override
    public Object selectById(Long id) {
        return courseAssessNameMapper.selectById(id);
    }


    @Override
    public void export(HttpServletResponse response, CourseassessName courseassessNamePo) throws Exception {
        try {
            // 1. 加载模板文件
            String templatePath = "test/doc/test1.docx";
            InputStream templateStream = getClass().getClassLoader().getResourceAsStream(templatePath);
            if (templateStream == null) {
                throw new FileNotFoundException("未找到模板文件：" + templatePath);
            }

            // 2. 准备数据
            Map<String, Object> dataMap = new HashMap<>();

            // 获取教师和课程信息
            Teacher teacher = teacherMapper.selectTeacherWithCourseByTeacherId(courseassessNamePo.getCourseId().longValue());
            String courseName = teacher.getCourse().getCourseName();
            if (teacher.getCourse().getCourseType().equals("1")){
                teacher.getCourse().setCourseType("专业课");
            }
            dataMap.put("title1", "《" + courseName + "》");

            Long courseId = Long.valueOf(courseassessNamePo.getCourseId());
            dataMap.put("course", teacher);
            dataMap.put("student_num", "70");

            // 获取课程评估数据
            List<Coureassess> programs = courseAssessService.list(courseId.intValue());
//================================================
            List<CourseAssessNameVo> list1 = new ArrayList<>();
            // 准备数据
            for (Coureassess program : programs) {
                CourseAssessNameVo courseAssessNameVo = new CourseAssessNameVo();
                courseAssessNameVo.setCourseassess(program.getCourseassess());
                courseAssessNameVo.setRequireType(program.getRequireType());
                //percent1
                List<CourseassessName> courseassessNameList1 = courseAssessNameMapper.selectByCourseAssessIdAndNames(program.getId().intValue(), "上机作业");
                Integer percent1 = 0;
                for (CourseassessName courseassessName : courseassessNameList1) {
                    percent1 += courseassessName.getPercent();
                }
                courseAssessNameVo.setPercent1(percent1);
                //percent2
                List<CourseassessName> courseassessNameList2 = courseAssessNameMapper.selectByCourseAssessIdAndNames(program.getId().intValue(), "课堂设计");
                Integer percent2 = 0;
                for (CourseassessName courseassessName : courseassessNameList2) {
                    percent2 += courseassessName.getPercent();
                }
                courseAssessNameVo.setPercent2(percent2);
                //percent3
                List<CourseassessName> courseassessNameList3 = courseAssessNameMapper.selectByCourseAssessIdAndNames(program.getId().intValue(), "项目报告");
                Integer percent3 = 0;
                for (CourseassessName courseassessName : courseassessNameList3) {
                    percent3 += courseassessName.getPercent();
                }
                courseAssessNameVo.setPercent3(percent3);
                //percent4
                List<CourseassessName> courseassessNameList4 = courseAssessNameMapper.selectByCourseAssessIdAndNames(program.getId().intValue(), "期末考试");
                Integer percent4 = 0;
                for (CourseassessName courseassessName : courseassessNameList4) {
                    percent4 += courseassessName.getPercent();
                }
                courseAssessNameVo.setPercent4(percent4);
                //sun
                courseAssessNameVo.setSun(percent1 +percent2 + percent3 + percent4);
                list1.add(courseAssessNameVo);
            }
//===============================================================
            List<CourseAssessNameVo> list2 = new ArrayList<>();

            for (Coureassess program : programs) {
                boolean innerFirstLoop = true;
                for (CourseassessName courseassessName : courseAssessNameMapper.selectByCourseAssessIdList(program.getId())) {
                    if (!courseassessName.getName().equals("达成度（%）")) {
                        CourseAssessNameVo courseAssessNameVo = new CourseAssessNameVo();
                        if (innerFirstLoop) {
                            courseAssessNameVo.setCourseassess(program.getCourseassess());
                            innerFirstLoop = false;
                        } else {
                            courseAssessNameVo.setCourseassess("");
                        }
                        courseAssessNameVo.setNames(courseassessName.getName());
                        courseAssessNameVo.setContents(courseassessName.getContent());
                        list2.add(courseAssessNameVo);
                    }
                }
            }

//=======================================================
            // 1. 每个目标的数据（a0, a1, a2, a3）
            List<Map<String, Double>> maps = new ArrayList<>();
            for (int i = 0; i < 4; i++) {
                maps.add(new HashMap<>());
            }

            for (int i = 0; i < Math.min(programs.size(), 4); i++) {
                Coureassess program = programs.get(i);
                Map<String, Double> currentMap = maps.get(i);
                currentMap.put("average", program.getAverage());
                currentMap.put("middle", program.getMiddle());
                currentMap.put("piancha", program.getPiancha());
                currentMap.put("maxValue", program.getMaxValue());
                currentMap.put("minValue", program.getMinValue());
            }

            // 这里可以通过 maps.get(0)、maps.get(1)、maps.get(2)、maps.get(3) 来获取对应的 Map
            Map<String, Double> a0 = maps.get(0);
            Map<String, Double> a1 = maps.get(1);
            Map<String, Double> a2 = maps.get(2);
            Map<String, Double> a3 = maps.get(3);

            dataMap.put("a0",a0);
            dataMap.put("a1",a1);
            dataMap.put("a2",a2);
            dataMap.put("a3",a3);

            //平均值
            Map<String, Double> average = new HashMap<>();
            average.put("average1",(a0.get("average")+a1.get("average")+a2.get("average")+a3.get("average")) / 4);
            average.put("average2",(a0.get("middle")+a1.get("middle")+a2.get("middle")+a3.get("middle")) / 4);
            average.put("average3",(a0.get("piancha")+a1.get("piancha")+a2.get("piancha")+a3.get("piancha")) / 4);
            average.put("average4",(a0.get("maxValue")+a1.get("maxValue")+a2.get("maxValue")+a3.get("maxValue")) / 4);
            average.put("average5",(a0.get("minValue")+a1.get("minValue")+a2.get("minValue")+a3.get("minValue")) / 4);
            dataMap.put("average",average);
//========================================================
            //fenbu
            Map<String, Object> fenbu1 = new HashMap<>();
            Map<String, Object> fenbu2 = new HashMap<>();
            Map<String, Object> fenbu3 = new HashMap<>();
            Map<String, Object> fenbu4 = new HashMap<>();
            Map<String, Object> b = new HashMap<>();


            List<AchievementDistribution> achievementDistributions1 = achievementDistributionMapper.selectByCoureassessId(1);
            List<AchievementDistribution> achievementDistributions2 = achievementDistributionMapper.selectByCoureassessId(2);
            List<AchievementDistribution> achievementDistributions3 = achievementDistributionMapper.selectByCoureassessId(3);
            List<AchievementDistribution> achievementDistributions4 = achievementDistributionMapper.selectByCoureassessId(4);
            List<AchievementDistribution> achievementDistributions5 = achievementDistributionMapper.selectByCoureassessId(-1);


            packageFenbu(achievementDistributions1,fenbu1);
            packageFenbu(achievementDistributions2,fenbu2);
            packageFenbu(achievementDistributions3,fenbu3);
            packageFenbu(achievementDistributions4,fenbu4);


            String[] keys = {"vate1", "vate2", "vate3", "vate4", "vate5"};
            int index = 0;
            for (AchievementDistribution achievementDistribution : achievementDistributions5) {
                b.put(keys[index++], achievementDistribution.getProportion());
            }

            dataMap.put("fenbu1",fenbu1);
            dataMap.put("fenbu2",fenbu2);
            dataMap.put("fenbu3",fenbu3);
            dataMap.put("fenbu4",fenbu4);
            dataMap.put("b",b);

//==============================================
            dataMap.put("name1","上机作业\n" +
                    "期末考试\n");
            dataMap.put("name2","上机作业\n" +
                    "期末考试\n");
            dataMap.put("name3","项目报告\n" +
                    "期末考试\n");
            dataMap.put("name4","上机作业\n" +
                    "课堂设计\n" +
                    "期末考试\n");

//================================================
            dataMap.put("maxcourseassess","课程目标1");
            dataMap.put("min","课程目标2");
            dataMap.put("Info","202041030001\t李林、课程目标平均达成值为33.73%；20204103111李卓梁 达成值为24.38%；、20204103222\t刘念达成值为19.54%；");

            int totalStudents = scoreService.countStudentByCourseId(courseId.intValue());
            dataMap.put("studentNum", totalStudents);



             //针对每个课程考核项目添加学生信息和最大最小得分数据
                for (int i = 0; i < programs.size(); i++) {
                    Coureassess program = programs.get(i);
                    Score score = scoreService.selectMaxAndMin(courseId, Math.toIntExact(program.getId()));
                    dataMap.put("max" + i, score);

                    Coureassess ca = courseAssessService.selectCourseassessInfo(courseId, Math.toIntExact(program.getId()));
                    dataMap.put("courseassess" + (i + 1), ca);

                    List<StudentInfoVo> studentInfos = scoreService.selectStudentInfo(courseId, Math.toIntExact(program.getId()));
                    List<String> studentNames = new ArrayList<>();
                    for (StudentInfoVo student : studentInfos) {
                        studentNames.add(student.getStudentNo() + student.getStudentName());
                    }
                    int remaining = totalStudents - studentInfos.size();
                    dataMap.put("value" + i, remaining);
                    dataMap.put("student" + (i + 1), studentNames);
                }

//===========================================================

            // 示例：课程目标1的数据
//            Map<String, Object> jiegou1 = new HashMap<>();
//            Map<String, Object> jiegou2 = new HashMap<>();
//            Map<String, Object> jiegou3 = new HashMap<>();
//            Map<String, Object> jiegou4 = new HashMap<>();
//
//            String[] nameList = {"name1", "name2", "name3"};
//            String[] percentsList = {"percents1", "percents2", "percents3"};
//            String[] averagesList = {"averages1", "averages2", "averages3"};
//            int nameCount = 0;
//            int percentsCount = 0;
//            int averagesCount = 0;
//            for (Coureassess program : programs) {
//                jiegou1.put("content",program.getCourseassess()+program.getContent());
//                List<CourseassessName> courseassessNameList = courseAssessNameMapper.selectByCourseAssessIdList(program.getId());
//                for (CourseassessName courseassessName : courseassessNameList) {
//                    if (!courseassessName.getName().equals("达成度（%）")) {
//                        jiegou1.put(nameList[nameCount++], courseassessName.getName());
//                        jiegou1.put(percentsList[percentsCount++], courseassessName.getPercent());
//                    }
//                    CoureassessAverage coureassessAverage = coureassessAverageMapper.selectByCoureassessIdAndCoureassessNameId1(program.getId(), courseassessName.getId());
//                    jiegou1.put(averagesList[averagesCount++],coureassessAverage.getEvaAverage());
//                }
//                jiegou1.put("averageScore",program.getAverage());
//            }

// 1. 用数组代替 jiegou1/jiegou2/jiegou3/jiegou4
            Map<String, Object>[] jiegouArray = new HashMap[4];
            for (int i = 0; i < 4; i++) {
                jiegouArray[i] = new HashMap<>();
            }

// 2. 遍历数据时，通过下标动态选择 Map
            int targetIndex = 0; // 当前处理的课程目标索引
            for (Coureassess program : programs) {
                Map<String, Object> currentJiegou = jiegouArray[targetIndex]; // 动态获取当前Map

                currentJiegou.put("content", program.getCourseassess() + program.getContent());

                List<CourseassessName> nameList = courseAssessNameMapper.selectByCourseAssessIdList(program.getId());
                for (int i = 0; i < nameList.size(); i++) {
                    CourseassessName nameItem = nameList.get(i);
                    if (!nameItem.getName().equals("达成度（%）")) {
                        currentJiegou.put("names" + (i + 1), nameItem.getName());
                        currentJiegou.put("percents" + (i + 1), nameItem.getPercent());
                        CoureassessAverage coureassessAverage = coureassessAverageMapper.selectByCoureassessIdAndCoureassessNameId1(program.getId(), nameItem.getId());
                        currentJiegou.put("averages" + (i + 1), coureassessAverage.getEvaAverage());
                    }
                }
                currentJiegou.put("averageScore", program.getAverage());

                targetIndex++; // 处理下一个课程目标
            }

// 3. 将数组放入最终的 dataMap
//            Map<String, Object> dataMap = new HashMap<>();
            for (int i = 0; i < jiegouArray.length; i++) {
                dataMap.put("jiegou" + (i + 1), jiegouArray[i]);
            }


//=========================================================
            // 3. 配置表格循环渲染策略
            LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
            Configure config = Configure.builder()
                    .bind("programs", policy)  // 绑定表格循环策略
                    .bind("list1",policy)
                    .bind("list2",policy)
                    .build();

            // 5. 添加固定信息
            dataMap.put("cj", "60%");
            dataMap.put("cj_context", "上机作业、总结报告");
            dataMap.put("ks", "40%");
            dataMap.put("ks_context", "期末大作业");



            // 4. 加载模板并渲染数据
            // 注意：这里直接从InputStream加载模板，避免路径编码问题
            XWPFTemplate template = XWPFTemplate.compile(templateStream, config)
                    .render(new HashMap<String, Object>() {{
                        putAll(dataMap);  // 添加所有简单数据
                        put("programs", programs);  // 添加表格循环数据
                        put("list1",list1);
                        put("list2",list2);

                    }});


            // 5. 设置响应头
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode("课程评估报告.docx", StandardCharsets.UTF_8.name()));

            // 6. 输出文档
            try (ServletOutputStream os = response.getOutputStream()) {
                template.write(os);
                os.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException("导出课程评估报告失败", e);
        }
    }

    void packageFenbu(List<AchievementDistribution> achievementDistributions,Map<String,Object> fenbu){
        String[] keys = {"A", "vate1", "B", "vate2", "C", "vate3", "D", "vate4", "E", "vate5"};
        int index = 0;
        for (AchievementDistribution achievementDistribution : achievementDistributions) {
            fenbu.put(keys[index++], achievementDistribution.getStuNumber());
            fenbu.put(keys[index++], achievementDistribution.getProportion());
        }
    }


//    @Override
//    public void export(HttpServletResponse response, CourseassessName courseassessNamePo) throws Exception {
//            try {
//                // 1. 加载模板文件（课程评价报告模板）
//                String templatePath = "test/doc/test1.docx";
//                URL templateUrl = getClass().getClassLoader().getResource(templatePath);
//                if (templateUrl == null) {
//                    throw new FileNotFoundException("未找到模板文件：" + templatePath);
//                }
//                String decodedTemplatePath = URLDecoder.decode(templateUrl.getPath(), StandardCharsets.UTF_8.name());
//                //log.info("模板文件路径：{}", decodedTemplatePath);
//
//                // 2. 初始化循环行表格渲染策略（用于动态表格）
//                LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
//
//                // 3. 查询相关数据
//                Teacher teacher = teacherMapper.selectTeacherWithCourseByTeacherId(courseassessNamePo.getCourseId().longValue());
//                //log.info("教师信息：{}", teacher);
//
//                Long courseId = Long.valueOf(courseassessNamePo.getCourseId());
//                //log.info("课程ID：{}", courseId);
//
//                List<Coureassess> programs = courseAssessService.list(courseId.intValue());
//
//                // 4. 构造数据Map，用于模板数据填充
//                Map<String, Object> dataMap = new HashMap<>();
//                dataMap.put("programs", programs);
//                dataMap.put("title1", "《JavaEE开发框架》");
//                dataMap.put("course", teacher);
//
//                // 用于存放各部分数据的集合
//                List<CourseAssessNameVo> list1 = new ArrayList<>();
//                List<CourseAssessNameVo> list2 = new ArrayList<>();
//                List<List<String>> nameList = new ArrayList<>();
//                List<CourseassessVo> courseAssessVoList = new ArrayList<>();
//                List<ScoreVo> scoreVoList = new ArrayList<>();
//
//                // 遍历各个课程考核项目
//                for (Coureassess program : programs) {
//                    // 4.1 处理课程评价名称及百分比信息
//                    CourseassessName baseName = courseAssessNameMapper.selectByCourseAssessId(program.getId());
//                    List<CourseassessName> subNames = courseAssessNameMapper.selectCourseassessNameByParentId(program.getId(), baseName.getId());
//
//                    CourseAssessNameVo vo = new CourseAssessNameVo();
//                    vo.setCourseassess(program.getCourseassess());
//                    vo.setRequireType(program.getRequireType());
//                    if (subNames.size() >= 4) { // 假设至少有4个子项
//                        vo.setPercent1(subNames.get(0).getPercent());
//                        vo.setPercent2(subNames.get(1).getPercent());
//                        vo.setPercent3(subNames.get(2).getPercent());
//                        vo.setPercent4(subNames.get(3).getPercent());
//                        int totalPercent = subNames.get(0).getPercent() + subNames.get(1).getPercent() +
//                                subNames.get(2).getPercent() + subNames.get(3).getPercent();
//                        vo.setSun(totalPercent);
//                    }
//                    list1.add(vo);
//
//                    // 4.2 拼接各子项的名称、内容、百分比及计算平均分
//                    StringBuilder namesBuilder = new StringBuilder();
//                    StringBuilder contentsBuilder = new StringBuilder();
//                    StringBuilder percentBuilder = new StringBuilder();
//                    StringBuilder scoreBuilder = new StringBuilder();
//                    double averageScore = 0.0;
//
//                    // 遍历子项，获取详细内容和评分
//                    for (CourseassessName subName : subNames) {
//                        // 获取下一级详情（若存在）
//                        List<CourseassessName> detailNames = courseAssessNameMapper.selectCourseassessNameByParentId(program.getId(), subName.getId());
//                        if (!detailNames.isEmpty()) {
//                            for (CourseassessName detail : detailNames) {
//                                namesBuilder.append(detail.getName()).append("\n\r");
//                                contentsBuilder.append(detail.getCoureassess().getContent()).append("\n\r");
//                            }
//                        }
//                        // 处理百分比和分值
//                        List<CourseassessName> percentItems = courseAssessNameMapper.selectCourseassessNameByParentId(program.getId(), subName.getId());
//                        if (percentItems != null) {
//                            for (CourseassessName item : percentItems) {
//                                if (item != null) {
//                                    percentBuilder.append(item.getPercent()).append("\n\r");
//                                    // 根据课程考核名称查询得分（注意：此处需保证 scoreService 方法能处理对应逻辑）
//                                    Double score = scoreService.selectScoreByName(item.getName(), courseId);
//                                    if (score != null) {
//                                        averageScore += score * item.getPercent() / 100.0;
//                                    }
//                                    scoreBuilder.append(score).append("\n\r");
//                                }
//                            }
//                        }
//                    }
//                    // 封装名称和内容信息
//                    CourseAssessNameVo voDetail = new CourseAssessNameVo();
//                    voDetail.setCourseassess(program.getCourseassess());
//                    voDetail.setNames(namesBuilder.toString());
//                    voDetail.setContents(contentsBuilder.toString());
//                    list2.add(voDetail);
//
//                    // 封装课程评价信息
//                    CourseassessVo caVo = new CourseassessVo();
//                    caVo.setContent(program.getContent());
//                    caVo.setNames(namesBuilder.toString());
//                    caVo.setPercents(percentBuilder.toString());
//                    caVo.setAverages(scoreBuilder.toString());
//                    caVo.setAverageScore(averageScore);
//                    courseAssessVoList.add(caVo);
//
//                    // 查询评分分布信息
//                    ScoreVo scoreVo = scoreService.selectFenbu(Math.toIntExact(program.getId()));
//                    scoreVoList.add(scoreVo);
//
//                    // 构造课程考核名称集合
//                    Map<String, Object> paramMap = new HashMap<>();
//                    paramMap.put("courseId", courseId);
//                    paramMap.put("coureassessId", program.getId());
//                    List<CourseassessName> nameEntries = courseAssessNameMapper.selectName(paramMap);
//                    List<String> names = new ArrayList<>();
//                    for (CourseassessName entry : nameEntries) {
//                        names.add(entry.getName());
//                    }
//                    nameList.add(names);
//                }
//
//                // 将整理后的数据放入Map中供模板渲染使用
//                dataMap.put("list1", list1);
//                dataMap.put("list2", list2);
//                dataMap.put("jieguo", courseAssessVoList);
//
//                // 绑定循环行渲染策略（对于动态表格数据）
//                Configure config = Configure.builder()
//                        .bind("programs", policy)
//                        .bind("list1", policy)
//                        .bind("list2", policy)
//                        .bind("jieguo", policy)
//                        .build();
//                XWPFTemplate template = XWPFTemplate.compile(decodedTemplatePath, config);
//
//                // 5. 添加固定信息
//                dataMap.put("cj", "60%");
//                dataMap.put("cj_context", "上机作业、总结报告");
//                dataMap.put("ks", "40%");
//                dataMap.put("ks_context", "期末大作业");
//
//                String maxCourseAssess = courseAssessService.selectCourseassessMaxByCourseId(courseId);
//                String minCourseAssess = courseAssessService.selectCourseassessByMin(courseId);
//                dataMap.put("maxcourseassess", maxCourseAssess);
//                dataMap.put("min", minCourseAssess);
//
//                int totalStudents = scoreService.countStudentByCourseId(courseId.intValue());
//                dataMap.put("studentNum", totalStudents);
//
//                List<Score> studentScores = scoreService.selectStudentByCourseId(courseId);
//                dataMap.put("student_num", studentScores.size());
//
//                List<String> studentInfoList = new ArrayList<>();
//                for (Score score : studentScores) {
//                    String info = score.getStudentNo() + score.getStudentName() + "课程目标平均达成值为" + score.getScore() + "%";
//                    studentInfoList.add(info);
//                }
//                dataMap.put("Info", studentInfoList);
//
//                // 针对每个课程考核项目添加学生信息和最大最小得分数据
//                for (int i = 0; i < programs.size(); i++) {
//                    Coureassess program = programs.get(i);
//                    Score score = scoreService.selectMaxAndMin(courseId, Math.toIntExact(program.getId()));
//                    dataMap.put("max" + i, score);
//
//                    Coureassess ca = courseAssessService.selectCourseassessInfo(courseId, Math.toIntExact(program.getId()));
//                    dataMap.put("courseassess" + (i + 1), ca);
//
//                    List<StudentInfoVo> studentInfos = scoreService.selectStudentInfo(courseId, Math.toIntExact(program.getId()));
//                    List<String> studentNames = new ArrayList<>();
//                    for (StudentInfoVo student : studentInfos) {
//                        studentNames.add(student.getStudentNo() + student.getStudentName());
//                    }
//                    int remaining = totalStudents - studentInfos.size();
//                    dataMap.put("value" + i, remaining);
//                    dataMap.put("student" + (i + 1), studentNames);
//                }
//
//                // 6. 添加资源信息
//                Resource resource = resourceMapper.selectByCourseId(courseId);
//                dataMap.put("resource", resource.getResource());
//                dataMap.put("methods", resource.getMethods());
//
//                // 7. 加载表格模板（另一个文档文件）
//                String tableTemplatePath = "test/doc/table.docx";
//                URL tableUrl = getClass().getClassLoader().getResource(tableTemplatePath);
//                if (tableUrl == null) {
//                    throw new FileNotFoundException("未找到表格模板：" + tableTemplatePath);
//                }
//                String decodedTablePath = URLDecoder.decode(tableUrl.getPath(), StandardCharsets.UTF_8.name());
//                //log.info("表格模板路径：{}", decodedTablePath);
//
//                // 8. 导出Word文档（使用WordExportUtil导出带数据的文档）
//                XWPFDocument document = WordExportUtil.exportWord07(decodedTablePath, dataMap);
//                response.setCharacterEncoding(StandardCharsets.UTF_8.name());
//                response.setContentType("application/octet-stream");
//                response.setHeader("Content-Disposition", "attachment;filename="
//                        + URLEncoder.encode("学生基本信息表.docx", StandardCharsets.UTF_8.name()));
//
//                // 写入响应流，采用 try-with-resources 确保流自动关闭
//                try (ServletOutputStream os = response.getOutputStream()) {
//                    document.write(os);
//                }
//                document.close();
//
//                // 9. 渲染模板并写回文件（如有需要保存到服务器端）
//                template.render(dataMap);
//                try (FileOutputStream fos = new FileOutputStream(decodedTablePath)) {
//                    template.writeAndClose(fos);
//                }
//            } catch (Exception e) {
//                //log.error("导出课程评价报告时出错：", e);
//                // 根据需要返回错误信息或进一步处理异常
//            }
//    }





    /*
    @Override
    public void export(HttpServletResponse response,CourseassessName courseassessNamePo) throws Exception {
        //获取模板
//        String path="C:\\Sxl\\test1.docx";
        String filePath = "test/doc/test1.docx";
        URL resourceUrl = getClass().getClassLoader().getResource(filePath);
        String resourcePath = resourceUrl.getPath();
        String filePath1 = URLDecoder.decode(resourcePath, "UTF-8");
        System.out.println(resourcePath);
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Teacher teacher =teacherMapper.selectTeacherWithCourseByTeacherId(1L);
//        Integer courseId = teacherMapper.selectCourseIdByTeacherId(teacher.getTeacherId());
        System.out.println(courseassessNamePo.getCourseId());
        List<Coureassess> programs = courseAssessService.list(courseassessNamePo.getCourseId());
        Map<String,Object> map = new HashMap<>();
        map.put("programs",programs);
        map.put("title1","《JavaEE开发框架》");
        map.put("course",teacher);
//        log.info(teacher.toString());
        System.out.println(teacher);
        ArrayList<CourseAssessNameVo> arrayList=new ArrayList<>();
        ArrayList<CourseAssessNameVo>arrayList2=new ArrayList<>();
        ArrayList<ArrayList<String>>arrayList3=new ArrayList<>();
        ArrayList<ArrayList<String>>arrayList4=new ArrayList<>();
        List<CourseassessVo>courseassessVos=new ArrayList<>();
        List<ScoreVo>scoreVos=new ArrayList<>();
        int a=0;
        for(Coureassess item:programs){
            ArrayList<String>courseAssessNameVos=new ArrayList<>();
            CourseassessName courseassessName= courseAssessNameMapper.selectByCourseAssessId(item.getId());
           List<CourseassessName>courseassessNameList1=courseAssessNameMapper.selectCourseassessNameByParentId(item.getId(),courseassessName.getId());
            CourseAssessNameVo courseAssessNameVo=new CourseAssessNameVo();
            courseAssessNameVo.setCourseassess(item.getCourseassess());
            courseAssessNameVo.setRequireType(item.getRequireType());
            int sum=0;
            courseAssessNameVo.setPercent1(courseassessNameList1.get(0).getPercent());
            courseAssessNameVo.setPercent2(courseassessNameList1.get(1).getPercent());
            courseAssessNameVo.setPercent3(courseassessNameList1.get(2).getPercent());
            courseAssessNameVo.setPercent4(courseassessNameList1.get(3).getPercent());
            sum=sum+courseassessNameList1.get(0).getPercent()+courseassessNameList1.get(1).getPercent()+courseassessNameList1.get(2).getPercent()+courseassessNameList1.get(3).getPercent();
            courseAssessNameVo.setSun(sum);
            arrayList.add(courseAssessNameVo);


            StringBuilder stringBuilder=new StringBuilder();
            StringBuilder stringBuilder1=new StringBuilder();

            double sum1=0.00;
            ArrayList<String>list1=new ArrayList<>();

            String s=null;
            StringBuilder builder=new StringBuilder();
            StringBuilder builder1=new StringBuilder();
            StringBuilder builder2=new StringBuilder();
            List<CourseassessName>courseassessNameList=new ArrayList<>();
            for(CourseassessName courseassessName1:courseassessNameList1){
                List<CourseassessName> courseassessNames = courseAssessNameMapper.selectCourseassessNameByParentId(item.getId(),courseassessName1.getId());
                if(courseassessNames.size()!=0){


                    for ( CourseassessName c:courseassessNames
                    ) {
                        stringBuilder.append(c.getName());
                        stringBuilder.append("\n\r");
                        stringBuilder1.append(c.getCoureassess().getContent());
                        stringBuilder1.append("\n\r");


                    }

                }
                courseassessNameList= courseAssessNameMapper.selectCourseassessNameByParentId(item.getId(),courseassessName1.getId());
//                if(courseassessNameList.size()!=0)
//                   {
                    for(CourseassessName courseassessName2:courseassessNameList){
                        if(courseassessName2!=null){
                            builder.append(courseassessName2.getName());
                            builder.append("\n\r");
                            builder1.append(courseassessName2.getPercent());
                            builder1.append("\n\r");
                            System.out.println(courseassessNamePo.getCourseId());
                            Double score1= scoreService.selectScoreByName(courseassessName2.getName(), Long.valueOf(courseassessNamePo.getCourseId()));
                            if(score1!=null){
                                sum1=sum1+score1*courseassessName2.getPercent()/100;
                            }
                            builder2.append(score1);
                            builder2.append("\n\r");
                            arrayList4.add(list1);
                        }

//                    }

                }
            }
            CourseAssessNameVo courseAssessNameVo1=new CourseAssessNameVo();
            courseAssessNameVo1.setCourseassess(item.getCourseassess());
            courseAssessNameVo1.setNames(String.valueOf(stringBuilder));
            courseAssessNameVo1.setContents(String.valueOf(stringBuilder1));
            arrayList2.add(courseAssessNameVo1);

            CourseassessVo courseassessVo=new CourseassessVo();
            courseassessVo.setContent(item.getContent());
            courseassessVo.setNames(String.valueOf(builder));
            courseassessVo.setPercents(String.valueOf(builder1));
            courseassessVo.setAverages(String.valueOf(builder2));
            courseassessVos.add(courseassessVo);
            courseassessVos.get(a).setAverageScore(sum1);
            a++;

            ScoreVo scoreVo = scoreService.selectFenbu(Math.toIntExact(item.getId()));
            scoreVos.add(scoreVo);
            ArrayList<String>arrayList1=new ArrayList<>();
            Map<String,Object>map1=new HashMap<>();
            map1.put("courseId",courseassessNamePo.getCourseId());
            map1.put("coureassessId",item.getId());
            List<CourseassessName>courseassessNames1= courseAssessNameMapper.selectName(map1);
            for (CourseassessName c:courseassessNames1
            ) {
                arrayList1.add(c.getName());
            }
            arrayList3.add(arrayList1);
            ArrayList<String>list=new ArrayList<>();



            //List<Score>scores=scoreService.selectNameByTeacherId(teacher.getTeacherId(),item.getId());

//            for (Score score : scores) {
////                s=s+score.getWokeName();
////                builder.append(score.getWokeName());
////                builder.append("\r");
//                //课程目标达成情况客观评价结果
//                Score score1= scoreService.selectScoreByName(score.getWokeName(),teacher.getTeacherId());
////                builder1.append(score1.getPercents());
////                builder1.append("\r");
//                sum1=sum1+score1.getAverage()*score1.getPercents()/100;
//               builder2.append(score1.getAverage());
//                builder2.append("\r");
//                arrayList4.add(list1);
//            }

        };
        map.put("list1",arrayList);
        map.put("list2",arrayList2);
        List<Coureassess> finishAverage = courseAssessService.caluationAverage(courseassessNamePo.getCourseId());
        for(int i=0;i<finishAverage.size();i++){
            if(finishAverage.get(i)!=null){
                map.put("a"+i,finishAverage.get(0));
            }
        }

//        map.put("a1",finishAverage.get(1));
//        map.put("a2",finishAverage.get(2));
//        map.put("a3",finishAverage.get(3));
        AverageVo averageVo= courseAssessService.selectAverage(Long.valueOf(courseassessNamePo.getCourseId()));
        map.put("average",averageVo);
        for (int i=0;i<scoreVos.size();i++){
            if(scoreVos.get(i)!=null){
                map.put("fenbu"+(i+1),scoreVos.get(i));
            }
        }

//        map.put("fenbu2",scoreVos.get(1));
//        map.put("fenbu3",scoreVos.get(2));
//        map.put("fenbu4",scoreVos.get(3));
        ScoreVo scoreVo = scoreService.countRate(courseassessNamePo.getCourseId());
        map.put("b",scoreVo);
        for(int i=0;i<arrayList3.size();i++){
            if(arrayList3.get(i)!=null){
                map.put("name"+(i+1),arrayList3.get(i));
            }
        }

//        map.put("name2",arrayList3.get(1));
//        map.put("name3",arrayList3.get(2));
//        map.put("name4",arrayList3.get(3));
        map.put("jieguo",courseassessVos);
        Configure config = Configure.builder()
                .bind("programs", policy)
                .bind("list1",policy)
                .bind("list2",policy)
                .bind("jieguo",policy).build();
        XWPFTemplate template = XWPFTemplate.compile(filePath1,config);  // 读取模板内容

        map.put("cj","60%");
        map.put("cj_context","上机作业、总结报告");
        map.put("ks","40%");
        map.put("ks_context","期末大作业");
        String Max = courseAssessService.selectCourseassessMaxByCourseId(Long.valueOf(courseassessNamePo.getCourseId()));
        String Min = courseAssessService.selectCourseassessByMin(Long.valueOf(courseassessNamePo.getCourseId()));
        map.put("maxcourseassess",Max);
        map.put("min",Min);
        int sum = scoreService.countStudentByCourseId(courseassessNamePo.getCourseId());
        map.put("studentNum",sum);
        List<Score> scores = scoreService.selectStudentByCourseId(Long.valueOf(courseassessNamePo.getCourseId()));
        map.put("student_num",scores.size());
        ArrayList<String>stringArrayList=new ArrayList<>();
        for(int i=0;i<scores.size();i++){
            String s1=scores.get(i).getStudentNo()+""+scores.get(i).getStudentName()+"课程目标平均达成值为"+scores
                    .get(i).getScore()+"%";
            stringArrayList.add(s1);
        }
//        List<StudentInfoVo> scores1=new ArrayList<>();
        for(int i=0;i<programs.size();i++){
            List<StudentInfoVo> scores1=new ArrayList<>();
            ArrayList<String>arrayList1=new ArrayList<>();
            Score score= scoreService.selectMaxAndMin(Long.valueOf(courseassessNamePo.getCourseId()), Math.toIntExact(programs.get(i).getId()));
            map.put("max"+i,score);
            Coureassess coureassess = courseAssessService.selectCourseassessInfo(Long.valueOf(courseassessNamePo.getCourseId()), Math.toIntExact(programs.get(i).getId()));
            map.put("courseassess"+(i+1),coureassess);
            scores1 = scoreService.selectStudentInfo(Long.valueOf(courseassessNamePo.getCourseId()), Math.toIntExact(programs.get(i).getId()));
            for (int j=0;j<scores1.size();j++){
                String s=scores1.get(j).getStudentNo()+scores1.get(j).getStudentName();
                arrayList1.add(s);
            }
            int value= sum-scores1.size();
        map.put("value"+i,value);
        map.put("student"+(i+1),arrayList1);
        }

        map.put("Info",stringArrayList);


//        ArrayList<String>arrayList1=new ArrayList<>();
//        for (int i=0;i<scores1.size();i++){
//            String s=scores1.get(i).getStudentNo()+scores1.get(i).getStudentName();
//            arrayList1.add(s);
//        }
//        int value= sum-scores1.size();
//        map.put("value",value);
//        map.put("student1",arrayList1);
//        Score score1= scoreService.selectMaxAndMin(Long.valueOf(courseassessNamePo.getCourseId()),2);
//        map.put("max1",score1);
//        Coureassess coureassess1 = courseAssessService.selectCourseassessInfo(Long.valueOf(courseassessNamePo.getCourseId()), 2);
//        map.put("courseassess2",coureassess1);
//        List<StudentInfoVo> scores2 = scoreService.selectStudentInfo(Long.valueOf(courseassessNamePo.getCourseId()), 2);
//        ArrayList<String>stringArrayList1=new ArrayList<>();
//        for (int i=0;i<scores2.size();i++){
//            String s=scores2.get(i).getStudentNo()+scores2.get(i).getStudentName();
//            stringArrayList1.add(s);
//        }
//        int value1= sum-scores2.size();
//        map.put("value1",value1);
//        map.put("student2",stringArrayList1);
//        Score score2= scoreService.selectMaxAndMin(Long.valueOf(courseassessNamePo.getCourseId()),3);
//        map.put("max2",score2);
//        Coureassess coureassess2 = courseAssessService.selectCourseassessInfo(Long.valueOf(courseassessNamePo.getCourseId()), 3);
//        map.put("courseassess3",coureassess2);
//        List<StudentInfoVo> scores3= scoreService.selectStudentInfo(Long.valueOf(courseassessNamePo.getCourseId()), 3);
//        ArrayList<String>stringArrayList2=new ArrayList<>();
//        for (int i=0;i<scores3.size();i++){
//            String s=scores3.get(i).getStudentNo()+scores3.get(i).getStudentName();
//            stringArrayList2.add(s);
//        }
//        int value2= sum-scores3.size();
//        map.put("value2",value2);
//        map.put("student3",stringArrayList2);
//        Score score3= scoreService.selectMaxAndMin(Long.valueOf(courseassessNamePo.getCourseId()),4);
//        map.put("max3",score3);
//        Coureassess coureassess3 = courseAssessService.selectCourseassessInfo(Long.valueOf(courseassessNamePo.getCourseId()), 4);
//        map.put("courseassess4",coureassess3);
//        List<StudentInfoVo> scores4 = scoreService.selectStudentInfo(Long.valueOf(courseassessNamePo.getCourseId()), 4);
//        ArrayList<String>stringArrayList3=new ArrayList<>();
//        for (int i=0;i<scores4.size();i++){
//            String s=scores4.get(i).getStudentNo()+scores4.get(i).getStudentName();
//            stringArrayList3.add(s);
//        }
//        int value3= sum-scores4.size();
//        map.put("value3",value3);
//        map.put("student4",stringArrayList3);
//        List<Coureassess> coureassess4= courseAssessService.selectInfoByTeacherId(teacher.getTeacherId());
        Resource resource= resourceMapper.selectByCourseId(Long.valueOf(courseassessNamePo.getCourseId()));
        map.put("resource",resource.getResource());
        map.put("methods",resource.getMethods());
        String filePath2 = "test/doc/table.docx";
        URL resourceUrl1 = getClass().getClassLoader().getResource(filePath2);
        String resourcePath1 = resourceUrl1.getPath();
        String filePath3 = URLDecoder.decode(resourcePath1, "UTF-8");
        System.out.println(resourcePath);
        XWPFDocument document = WordExportUtil.exportWord07(filePath3, map);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            //设置内容类型
            response.setContentType("application/octet-stream");

            //设置头及文件命名。
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("学生基本信息表.docx", StandardCharsets.UTF_8.name()));

            //写入
            document.write(response.getOutputStream());
            document.close();
        template.render(map);
        template.writeAndClose(new FileOutputStream(filePath3));

    }

     */





    @Override
    public List<Integer> selectPercentByCourseAssessId(Integer integer,Integer courseId) {
        Map<String,Object>map=new HashMap<>();
        map.put("coureassessId",integer);
        map.put("courseId",courseId);
        return courseAssessNameMapper.selectPercentByCourseAssessId(map);
    }

}
